package com.yanqu.road.server.manger.activity;

import com.yanqu.road.entity.activity.ActivityConditionInfo;
import com.yanqu.road.entity.activity.ActivityInfo;
import com.yanqu.road.entity.activity.UserActivityConditionData;
import com.yanqu.road.entity.config.battle.BattleResult;
import com.yanqu.road.entity.config.battle.CrossBattleResult;
import com.yanqu.road.entity.config.goods.GoodsInfo;
import com.yanqu.road.entity.config.goods.MallInfo;
import com.yanqu.road.entity.enums.eActivityType;
import com.yanqu.road.entity.enums.eGamePlayerEventType;
import com.yanqu.road.entity.enums.eMailType;
import com.yanqu.road.entity.enums.eTradeWarBattleType;
import com.yanqu.road.entity.player.UserBaseInfo;
import com.yanqu.road.entity.player.UserInfo;
import com.yanqu.road.entity.player.UserPatrons;
import com.yanqu.road.entity.rank.yrank.UserYRank;
import com.yanqu.road.entity.servercenter.ServerInfo;
import com.yanqu.road.entity.task.args.UnionRiseRankArgs;
import com.yanqu.road.entity.tradewar.TradeWarActivityJoinUnion;
import com.yanqu.road.entity.tradewar.TradeWarWanted;
import com.yanqu.road.entity.tradewar.UserTradeWarInfo;
import com.yanqu.road.entity.tradewar.UserTradeWarRecord;
import com.yanqu.road.entity.union.UnionMember;
import com.yanqu.road.entity.union.activitygroup.UnionActivityGroup;
import com.yanqu.road.entity.union.activitygroup.UnionActivityGroupUnion;
import com.yanqu.road.entity.union.activitygroup.UnionActivityGroupUser;
import com.yanqu.road.entity.union.cross.CrossUnionInfo;
import com.yanqu.road.entity.union.cross.CrossUnionMember;
import com.yanqu.road.logic.bussiness.cross.CrossTradeWarBussiness;
import com.yanqu.road.logic.bussiness.player.UserActivityBussiness;
import com.yanqu.road.logic.bussiness.player.UserPatronsBussiness;
import com.yanqu.road.logic.bussiness.player.UserTradeWarActivityBussiness;
import com.yanqu.road.logic.bussiness.player.UserTradeWarBussiness;
import com.yanqu.road.logic.bussiness.tradewar.TradeWarActivityBussiness;
import com.yanqu.road.logic.config.GameConfig;
import com.yanqu.road.logic.helper.UnionActivityGroupHelper;
import com.yanqu.road.logic.pb.PlayerBasePb;
import com.yanqu.road.pb.cross.tradewar.CrossTradeWarProto;
import com.yanqu.road.pb.tradewar.TradeWarProto;
import com.yanqu.road.pb.tradewaractivity.TradeWarActivityProto;
import com.yanqu.road.server.GameServer;
import com.yanqu.road.server.TempMgr;
import com.yanqu.road.server.gameplayer.GamePlayer;
import com.yanqu.road.server.gameplayer.module.activity.ActivityMallModule;
import com.yanqu.road.server.gameplayer.module.activity.tradewar.TradeWarActivityModule;
import com.yanqu.road.server.gameplayer.module.patrons.PatronsModule;
import com.yanqu.road.server.gameplayer.module.player.TradeWarModule;
import com.yanqu.road.server.logic.activity.tradewar.TradeWarActivityData;
import com.yanqu.road.server.logic.battle.BattleManager;
import com.yanqu.road.server.logic.calc.CalculationManager;
import com.yanqu.road.server.logic.mail.MailManager;
import com.yanqu.road.server.manger.MultipleLanguageMgr;
import com.yanqu.road.server.manger.ServerListMgr;
import com.yanqu.road.server.manger.config.GoodsMgr;
import com.yanqu.road.server.manger.config.TradeWarConfigMgr;
import com.yanqu.road.server.manger.player.TradeWarMgr;
import com.yanqu.road.server.manger.player.UserMgr;
import com.yanqu.road.server.manger.player.GamePlayerMgr;
import com.yanqu.road.server.manger.rank.YRankMgr;
import com.yanqu.road.server.manger.union.CrossUnionMgr;
import com.yanqu.road.server.manger.union.GameUnionActivityGroupMgr;
import com.yanqu.road.server.pb.PlayerPb;
import com.yanqu.road.server.pb.TradeWarActivityPb;
import com.yanqu.road.logic.pb.TradeWarPb;
import com.yanqu.road.server.protocol.CrossProtocol;
import com.yanqu.road.utils.YanQuMessageUtils;
import com.yanqu.road.message.YanQuMessage;
import com.yanqu.road.server.protocol.GameErrorCode;
import com.yanqu.road.server.protocol.Protocol;
import com.yanqu.road.utils.RandomHelper;
import com.yanqu.road.utils.UUIDHelper;
import com.yanqu.road.utils.date.DateHelper;
import com.yanqu.road.utils.property.Property;
import com.yanqu.road.utils.property.PropertyHelper;
import com.yanqu.road.utils.string.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.math.BigDecimal;
import java.math.BigInteger;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;


public class TradeWarActivityMgr extends TempMgr {

    public static final int CONDITION_TYPE_USER = eGamePlayerEventType.CrossTradeWarScoreRiseRank.getValue();

    public static final int CONDITION_TYPE_UNION = eGamePlayerEventType.CrossTradeWarUnionScoreRiseRank.getValue();

    private static Logger logger = LogManager.getLogger(TradeWarActivityMgr.class.getName());

    private static ActivityInfo activityInfo;

    private static Map<Integer, List<ActivityConditionInfo>> activityConditionInfoMap = new ConcurrentHashMap<>();

    private static Map<Integer, MallInfo> activityMallInfoMap = new ConcurrentHashMap<>();

    private static Map<Integer,Map<Integer,TradeWarActivityJoinUnion>> tradeWarActivityJoinUnionMap = new ConcurrentHashMap<>();

    private static Map<Integer, Map<String, UserTradeWarRecord>> cacheTradeWarRecordMap = new ConcurrentHashMap<>();

    private static RandomHelper randomHelper = new RandomHelper();

    private static boolean isFirstGetCrossNotice = false;

    @Override
    public boolean stop() {
        return false;
    }

    @Override
    public boolean init() throws Exception {
        return reload();
    }

    @Override
    public boolean reloadConfig() throws Exception {
        return true;
    }

    @Override
    public boolean save() {
        for (Map<Integer,TradeWarActivityJoinUnion> unionMap:tradeWarActivityJoinUnionMap.values()){
            for(TradeWarActivityJoinUnion tradeWarActivityJoinUnion : unionMap.values()){
                if(tradeWarActivityJoinUnion.isInsertOption()){
                    TradeWarActivityBussiness.addTradeWarActivityJoinUnion(tradeWarActivityJoinUnion);
                }else if(tradeWarActivityJoinUnion.isUpdateOption()){
                    TradeWarActivityBussiness.updateTradeWarActivityJoinUnion(tradeWarActivityJoinUnion);
                }
            }
        }

        return true;
    }

    @Override
    public boolean reloadData() {
        activityInfo = null;
        Map<Integer,Map<Integer,TradeWarActivityJoinUnion>> tempTreadWarJoinUnionMapFromDb = TradeWarActivityBussiness.getTradeWarActivityJoinUnionMap();
        tradeWarActivityJoinUnionMap = tempTreadWarJoinUnionMapFromDb;

        activityConditionInfoMap = new ConcurrentHashMap<>();
        activityMallInfoMap = new ConcurrentHashMap<>();
        cacheTradeWarRecordMap = new ConcurrentHashMap<>();
        return true;
    }

    public static Map<Integer,Map<Integer,TradeWarActivityJoinUnion>>  getTradeWarActivityJoinUnionMap() {
        return tradeWarActivityJoinUnionMap;
    }

    public static void reloadActivityData(Map<Integer, ActivityInfo> selectActivityInfoMap, Map<Integer, Map<Integer, MallInfo>> selectActivityMallInfoMap,
                                          Map<Integer, Map<Integer, List<ActivityConditionInfo>>> selectActivityConditionInfoMap){
        logger.info("reload TradeWarActivity start");
        ActivityInfo inTimeActivity = null;
        Map<Integer, List<ActivityConditionInfo>> inTimeActivityConditionInfoMap = new ConcurrentHashMap<>();
        Map<Integer, MallInfo> inTimeActivityMallInfoMap = new ConcurrentHashMap<>();
        for(ActivityInfo activityInfo : selectActivityInfoMap.values()){
            if(ActivityMgr.activityInShowTime(activityInfo)){
                inTimeActivity = activityInfo;
                if(null != selectActivityConditionInfoMap.get(activityInfo.getActivityId())) {
                    inTimeActivityConditionInfoMap = selectActivityConditionInfoMap.get(activityInfo.getActivityId());
                }
                if(null != selectActivityMallInfoMap.get(activityInfo.getActivityId())){
                    inTimeActivityMallInfoMap = selectActivityMallInfoMap.get(activityInfo.getActivityId());
                }
                break;
            }
        }
        activityInfo = inTimeActivity;
        activityConditionInfoMap = inTimeActivityConditionInfoMap;
        activityMallInfoMap = inTimeActivityMallInfoMap;
        TradeWarActivityRankMgr.reloadRank();
        playerReloadActivity();
        logger.info("reload TradeWarActivity end");
    }

    public static void addToCacheTradeWarRecordMap(String recordUid,UserTradeWarRecord record, int groupId){
        if (groupId == UnionActivityGroupHelper.NO_GROUP_ID){
            return;
        }
        if (cacheTradeWarRecordMap.get(groupId)==null){
            synchronized (cacheTradeWarRecordMap){
                if (cacheTradeWarRecordMap.get(groupId)==null){
                    cacheTradeWarRecordMap.put(groupId,new ConcurrentHashMap<>());
                }
            }
        }
        cacheTradeWarRecordMap.get(groupId).put(recordUid,record);
    }

    public static Map<String, UserTradeWarRecord> getCacheTradeWarRecordMapByGroupId (int groupId){
        if (!cacheTradeWarRecordMap.containsKey(groupId)){
            return null;
        }
        return cacheTradeWarRecordMap.get(groupId);
    }

    private static void playerReloadActivity() {
        List<GamePlayer> playerList = GamePlayerMgr.getCopyPlayerList();
        playerList.forEach(action -> {
            action.getModule(TradeWarActivityModule.class).addNewActivity();
            action.getModule(TradeWarActivityModule.class).syncActivity();
            action.getModule(ActivityMallModule.class).syncMallBuyCount();
            action.getModule(ActivityMallModule.class).syncActivityScore();
        });
    }

    public static void initCrossTradeWarUnion(ActivityInfo activityInfo){
        boolean isNotify = false;

        Map<Integer, UnionActivityGroup> groupMap = GameUnionActivityGroupMgr.getGroupMap(activityInfo.getActivityId());
        if (groupMap == null){
            logger.error("跨服商战活动{}分组信息不存在,下次再初始化商会",activityInfo.getActivityId());
            return;
        }
        if (groupMap.isEmpty()){
            logger.error("跨服商战活动{}分组信息不存在,下次再初始化商会",activityInfo.getActivityId());
            return;
        }
        if(!tradeWarActivityJoinUnionMap.containsKey(activityInfo.getActivityId())){
            synchronized (tradeWarActivityJoinUnionMap){
                if(!tradeWarActivityJoinUnionMap.containsKey(activityInfo.getActivityId())){
                    tradeWarActivityJoinUnionMap.put(activityInfo.getActivityId(),new ConcurrentHashMap<>());
                    for (int groupId :groupMap.keySet()){
                        if (groupId == UnionActivityGroupHelper.NO_GROUP_ID){
                            continue;
                        }
                        if (!tradeWarActivityJoinUnionMap.get(activityInfo.getActivityId()).containsKey(groupId)){
                            TradeWarActivityJoinUnion tradeWarActivityJoinUnion = new TradeWarActivityJoinUnion();
                            tradeWarActivityJoinUnion.setActivityId(activityInfo.getActivityId());
                            tradeWarActivityJoinUnion.setGroupId(groupId);
                            if (groupId != UnionActivityGroupHelper.NO_NEED_GROUP_ID){  //新版活动的分组
                                UnionActivityGroup groupData = GameUnionActivityGroupMgr.getGroupData(activityInfo.getActivityId(), groupId);
                                if (groupData == null){
                                    logger.error("跨服商战活动，id{}，分组{}数据不存在",activityInfo.getActivityId(),groupId);
                                    return;
                                }
                                ConcurrentHashMap<String, UnionActivityGroupUnion> unionDataMap = groupData.getUnionDataMap();
                                ArrayList<UnionActivityGroupUnion> crossUnionInfos = new ArrayList<>(unionDataMap.values());
                                crossUnionInfos.sort(new Comparator<UnionActivityGroupUnion>() {
                                    @Override
                                    public int compare(UnionActivityGroupUnion o1, UnionActivityGroupUnion o2) {
                                        if (o1.getRank() < o2.getRank()){
                                            return -1;
                                        }else if (o1.getRank() > o2.getRank()){
                                            return 1;
                                        }else {
                                            return 0;
                                        }
                                    }
                                });
                                if (crossUnionInfos.isEmpty()) {
                                    return;
                                }
                                List<String> unionUidList = new ArrayList<>();
                                for(int i = 0; i < Integer.parseInt(activityInfo.getParam6()); i++){
                                    if(i >= crossUnionInfos.size()){
                                        break;
                                    }
                                    UnionActivityGroupUnion unionRank = crossUnionInfos.get(i);
                                    if(null == unionRank){
                                        break;
                                    }
                                    unionUidList.add(unionRank.getUnionUid());
                                }
                                tradeWarActivityJoinUnion.setUnionUidList(unionUidList);
                            } else {                            //旧版活动的分组
                                List<CrossUnionInfo> sortUnionList = CrossUnionMgr.getSortUnionList();
                                if (sortUnionList == null || sortUnionList.isEmpty()) {
                                    return;
                                }
                                List<String> unionUidList = new ArrayList<>();
                                for(int i = 0; i < Integer.parseInt(activityInfo.getParam6()); i++){
                                    if(i >= sortUnionList.size()){
                                        break;
                                    }
                                    CrossUnionInfo unionRank = sortUnionList.get(i);
                                    if(null == unionRank){
                                        break;
                                    }
                                    unionUidList.add(unionRank.getUnionUid());
                                }
                                tradeWarActivityJoinUnion.setUnionUidList(unionUidList);
                            }

                            tradeWarActivityJoinUnion.setInsertOption();

                            isNotify = true;
                            tradeWarActivityJoinUnionMap.get(activityInfo.getActivityId()).put(groupId,tradeWarActivityJoinUnion);
                            logger.info("跨服商战活动{}加载分组{}成功",activityInfo.getActivityId(),groupId);
                        }
                    }
                }
            }
        }
        if(isNotify){//有变动
            List<GamePlayer> playerList = GamePlayerMgr.getCopyPlayerList();
            for(GamePlayer player : playerList){//通知玩家跨服商战资格
                TradeWarModule tradeWarModule = player.getModule(TradeWarModule.class);
                tradeWarModule.syncCrossUserTradeWarBattle();
            }
            //每个分组去拿参与玩家 如果是本服的吧 就改一下数据
            for (UnionActivityGroup unionActivityGroup: groupMap.values()){
                for (UnionActivityGroupUnion union:unionActivityGroup.getUnionDataMap().values()){
                    for (UnionActivityGroupUser user : union.getUserMap().values()){
                        UserTradeWarInfo tradeWarInfo = TradeWarMgr.getUserTradeWarInfo(user.getUserId());
                        if(null != tradeWarInfo) {
                            if(tradeWarInfo.getActivityId() != activityInfo.getActivityId()) {
                                tradeWarInfo.setCrossScore(0);
                                tradeWarInfo.setCrossTradeWarMoney(0);
                                tradeWarInfo.setActivityId(activityInfo.getActivityId());
                                GamePlayer tempPlayer = GamePlayerMgr.getOnlinePlayer(tradeWarInfo.getUserId());
                                if(null == tempPlayer){
                                    UserTradeWarBussiness.updateUserTradeWarInfo(tradeWarInfo);
                                }
                            }
                        }
                    }
                }
            }
        }
    }

    public static List<String> getCrossTradeWarUnionList(int activityId, int groupId) {
        if (tradeWarActivityJoinUnionMap.containsKey(activityId)) {
            if (tradeWarActivityJoinUnionMap.get(activityId).containsKey(groupId)) {
                return tradeWarActivityJoinUnionMap.get(activityId).get(groupId).getUnionUidList();
            }
        }
        return null;
    }

    /**
     * 商会能否参与跨服商战
     */
    public static boolean unionCanCrossTradeWar(String unionUid){
        ActivityInfo activityInfo = getOpenActivityInfo();
        if(null == activityInfo){
            return false;
        }
        return unionCanCrossTradeWar(activityInfo.getActivityId(), unionUid);
    }

    private static boolean unionCanCrossTradeWar(int activityId, String unionUid){
        if(StringUtils.isNullOrEmpty(unionUid)){
            return false;
        }
        int groupId = GameUnionActivityGroupMgr.getGroupId(activityId, unionUid);
        List<String> unionList = getCrossTradeWarUnionList(activityId,groupId);
        if(null != unionList){
            return unionList.contains(unionUid);
        }
        return false;
    }

    /**
     * 玩家能否参与跨服商战
     */
    public static boolean canCrossTradeWar(long userId){
        ActivityInfo activityInfo = getOpenActivityInfo();
        if(null == activityInfo){
            return false;
        }
        return canCrossTradeWar(activityInfo.getActivityId(), userId);
    }

    public static boolean canCrossTradeWar(int activityId, long userId){
        int groupId = GameUnionActivityGroupMgr.getGroupId(activityId, userId);
        List<String> unionList = getCrossTradeWarUnionList(activityId,groupId);
//        UnionActivityGroupUnion unionData = GameUnionActivityGroupMgr.getUnionData(activityId, userId);
//        if (unionData != null){
        UserInfo userInfo = UserMgr.getUserInfo(userId);
        if (userInfo == null){
            return false;
        }
        String userInUnionUid = userInfo.getUnionUid();
        if (null != unionList) {
            for (String unionUid : unionList) {
                if (unionUid.equals(userInUnionUid)) {
                    return true;
                }
            }
        }

        return false;
    }

    public static MallInfo getMallInfo(int mallId){
        return activityMallInfoMap.get(mallId);
    }

    public static ActivityInfo getOpenActivityInfo(int activityId){
        if(ActivityMgr.activityInShowTime(activityInfo) && activityInfo.getActivityId() == activityId){
            return activityInfo;
        }
        return null;
    }

    public static ActivityInfo getInTimeActivityInfo(int activityId){
        if(ActivityMgr.activityInTime(activityInfo) && activityInfo.getActivityId() == activityId){
            return activityInfo;
        }
        return null;
    }

    public static ActivityInfo getOpenActivityInfo() {
        if (ActivityMgr.activityInShowTime(activityInfo)) {
            return activityInfo;
        }
        return null;
    }

    public static int getOpenActivityId(){
        ActivityInfo activityInfo = getOpenActivityInfo();
        if(null != activityInfo){
            return activityInfo.getActivityId();
        }
        return 0;
    }

    public static ActivityInfo getInTimeActivityInfo() {
        if (ActivityMgr.activityInTime(activityInfo)) {
            return activityInfo;
        }
        return null;
    }

    public static List<ActivityConditionInfo> getActivityConditionInfoList(int activityId, int type){
        ActivityInfo activityInfo = getOpenActivityInfo(activityId);
        if(null != activityInfo) {
            return activityConditionInfoMap.get(type);
        }
        return null;
    }

    public static ActivityConditionInfo getActivityConditionInfoByRank(int activityId, int type, int rank) {
        List<ActivityConditionInfo> dataList = getActivityConditionInfoList(activityId, type);
        if(null != dataList) {
            for (ActivityConditionInfo conditionInfo : dataList) {
                if (rank >= conditionInfo.getParamList().get(0).intValue() && rank <= conditionInfo.getParamList().get(1).intValue()) {
                    return conditionInfo;
                }
            }
        }
        return null;
    }

    public static ActivityConditionInfo getActivityConditionInfo(int activityId, int conditionId) {
        Map<Integer, List<ActivityConditionInfo>> dataMap = getActivityConditionInfoMap(activityId);
        if(null != dataMap) {
            for (List<ActivityConditionInfo> conditionInfoList : dataMap.values()) {
                for (ActivityConditionInfo conditionInfo : conditionInfoList) {
                    if (conditionId == conditionInfo.getConditionId()) {
                        return conditionInfo;
                    }
                }
            }
        }
        return null;
    }

    public static int getMaxRankByType(int activityId, int type) {
        int maxRank = 0;
        List<ActivityConditionInfo> dataList = getActivityConditionInfoList(activityId, type);
        if(null != dataList) {
            for (ActivityConditionInfo conditionInfo : dataList) {
                if (conditionInfo.getParamList().get(1).intValue() > maxRank) {
                    maxRank = conditionInfo.getParamList().get(1).intValue();
                }
            }
        }
        return maxRank;
    }

    public static Map<Integer, List<ActivityConditionInfo>> getActivityConditionInfoMap(int activityId) {
        ActivityInfo activityInfo = getOpenActivityInfo(activityId);
        if(null != activityInfo) {
            return activityConditionInfoMap;
        }
        return null;
    }

    public static TradeWarActivityProto.TradeWarActivityDetailMsg.Builder getTradeWarActivityDetailMsg(Map<Integer, TradeWarActivityData> activityDataMap, String language){
        return TradeWarActivityPb.parseTradeWarActivityDetailMsg(activityDataMap, activityInfo, activityConditionInfoMap, activityMallInfoMap, language);
    }

    /**
     * 跨服商战战斗开始
     */
    public static CrossBattleResult toEnemyBattle(int activityId, int battleType, long enemyUserId, long myUserId, List<UserPatrons> patronsList,
                                                  int useItemId, int buyBuffTimes, int addScoreSkillAddition, int loseScoreSkillAddition, UserBaseInfo myBaseInfo, long myScore,
                                                  boolean isWantedOverTime, int rewardSkillAddition, int wantedItemId, int fastTeamNum) {
        GamePlayer player = GamePlayerMgr.getOnlinePlayer(enemyUserId);
        Map<Integer, UserPatrons> enemyPatronsMap;
        if(null != player){
            enemyPatronsMap = player.getModule(PatronsModule.class).getUserPatronsMap();
        }else {
            enemyPatronsMap = UserPatronsBussiness.getUserPatronsMap(enemyUserId);
        }
        List<UserPatrons> enemyPatronsList = new ArrayList<>(enemyPatronsMap.values());
        //打乱对面人才
        enemyPatronsList = TradeWarConfigMgr.disorganizeOrder(enemyPatronsList);

        //buff加成
        int buffAddition = TradeWarConfigMgr.getCrossTradeWarBuffAddition(buyBuffTimes);
        BattleResult battleResult = BattleManager.battle(myUserId, patronsList, enemyUserId, enemyPatronsList, buffAddition, true, false);

        CrossBattleResult crossBattleResult = new CrossBattleResult();
        crossBattleResult.setBattleResult(battleResult);
        crossBattleResult.setBattleType(battleType);
        crossBattleResult.setWantedItemId(wantedItemId);
        int tempBattleType = crossBattleResult.getBattleType();
        if(isWantedOverTime){
            crossBattleResult.setTrackChangeType(eTradeWarBattleType.Challenge.getValue());
        }
        //计算对手丢失分数
        calcCrossEnemyLoseScore(crossBattleResult, useItemId, addScoreSkillAddition, loseScoreSkillAddition);
        int groupId = GameUnionActivityGroupMgr.getGroupId(activityId, myUserId);

        if(crossBattleResult.getBattleType() == eTradeWarBattleType.Track.getValue() &&
                !TradeWarConfigMgr.isCrossTrackChange(crossBattleResult.getTrackChangeType())){//需要先到跨服确定是否追缉完
            UserTradeWarRecord record = initCrossRecord(activityId, crossBattleResult.getBattleType(), myScore + crossBattleResult.getMyAddScore(),
                    crossBattleResult.getKillPatronsCount(), crossBattleResult.getEnemyLoseScore(), enemyUserId, myUserId, myBaseInfo);
            addToCacheTradeWarRecordMap(record.getRecordUid(), record,groupId);
            crossBattleResult.setRecordUid(record.getRecordUid());
        }else {
            if(crossBattleResult.getBattleType() == eTradeWarBattleType.Track.getValue() &&
                    TradeWarConfigMgr.isCrossTrackChange(crossBattleResult.getTrackChangeType())){//没有追击成功
                crossBattleResult.setEnemyLoseScore(0);
            }
            //变更积分
            if(crossBattleResult.getEnemyLoseScore() > 0 && !TradeWarConfigMgr.isCrossTrackChange(crossBattleResult.getTrackChangeType())) {
                TradeWarActivityMgr.changeCrossTradeWarScore(enemyUserId, 0 - crossBattleResult.getEnemyLoseScore());
            }
            //被击杀任务、成就
            TradeWarMgr.notifyEnemyBeKillPatronsCount(enemyUserId, battleResult.getKillPatronsCount());
            //本服增加记录
            if(TradeWarConfigMgr.isCrossTrackChange(crossBattleResult.getTrackChangeType())){
                tempBattleType = crossBattleResult.getTrackChangeType();
            }
            addCrossRecord(activityId, tempBattleType, myScore + crossBattleResult.getMyAddScore(), crossBattleResult.getKillPatronsCount(),
                    crossBattleResult.getEnemyLoseScore(), enemyUserId, myUserId, myBaseInfo);
        }
        //记录对手基础信息
        crossBattleResult.setEnemyBaseInfo(UserMgr.getUserBaseInfo(enemyUserId, GameServer.getInstance().getServerId()));
        //设置击败奖励
        Property battleReward = getCrossTradeWarReward(tempBattleType, battleResult.getKillPatronsCount(), useItemId, rewardSkillAddition, wantedItemId);
        crossBattleResult.setReward(PropertyHelper.parsePropertyToString(battleReward));
        crossBattleResult.setTeamIndex(fastTeamNum);
        return crossBattleResult;
    }

    /**
     * 通知对手服加记录
     * @param enemyUserId
     * @param battleType
     * @param recordUid
     * @param killPatronsCount
     * @param enemyLoseScore
     */
    public static void notifyEnemyAddRecord(long enemyUserId, int battleType, String recordUid, int killPatronsCount, int enemyLoseScore, boolean isCancel){
        int groupId = GameUnionActivityGroupMgr.getGroupId(activityInfo.getActivityId(), enemyUserId);
        if (groupId == UnionActivityGroupHelper.NO_GROUP_ID){
            logger.error("玩家{}所在分组错误",enemyUserId);
        }
        Map<String, UserTradeWarRecord> cacheTradeWarRecordMapByGroupId = getCacheTradeWarRecordMapByGroupId(groupId);
        if (cacheTradeWarRecordMapByGroupId == null){
            logger.error("玩家{}所在分组未初始化",enemyUserId);
            return;
        }
        UserTradeWarRecord record = cacheTradeWarRecordMapByGroupId.get(recordUid);
        cacheTradeWarRecordMap.remove(recordUid);
        if(!isCancel) {
            if (battleType == eTradeWarBattleType.Track.getValue()) {
                if (enemyLoseScore > 0) {//变更积分
                    TradeWarActivityMgr.changeCrossTradeWarScore(enemyUserId, 0 - enemyLoseScore);
                }
            } else {//追缉超过人数，不扣分
                if (null != record) {
                    record.setBattleType(battleType);
                    record.setLoseScore(0);
                }
            }
            //被击杀任务、成就
            TradeWarMgr.notifyEnemyBeKillPatronsCount(enemyUserId, killPatronsCount);
            //增加记录
            if (null != record) {
                enemyAddCrossRecord(enemyUserId, record);
            }
        }
    }

    /**
     * 修改跨服对手分数
     * @param battleResult 战斗结果
     * @param useItemId 使用道具编号
     * @param loseScoreSkillAddition 增加伤害技能加成
     */
    public static void calcCrossEnemyLoseScore(CrossBattleResult battleResult, int useItemId, int addScoreSkillAddition, int loseScoreSkillAddition) {
        //使用道具加成效果
        GoodsInfo goodsInfo = null;
        if(useItemId > 0) {
            goodsInfo = GoodsMgr.getGoodsById(useItemId);
        }
        if (battleResult.getKillPatronsCount() > 0) {
            int addScore = battleResult.getKillPatronsCount() * 2;
            if(null != goodsInfo){
                addScore = addScore * goodsInfo.getParamList().get(0).intValue();
            }
            if(battleResult.getBattleType() == eTradeWarBattleType.Track.getValue() &&
                    battleResult.getTrackChangeType() != eTradeWarBattleType.Challenge.getValue()){//追缉则增加倍数
                GoodsInfo wantedGoods = GoodsMgr.getGoodsById(battleResult.getWantedItemId());
                if(null != wantedGoods){
                    int param2 = wantedGoods.getParamList().get(1).intValue();
                    addScore = addScore * param2;
                }
            }
            BigDecimal val1 = BigDecimal.valueOf(1000 + addScoreSkillAddition).divide(BigDecimal.valueOf(1000), CalculationManager.CALCULATION_SCALE,
                    BigDecimal.ROUND_UP);
            BigDecimal val2 = val1.multiply(BigDecimal.valueOf(addScore));
            addScore = val2.setScale(0, BigDecimal.ROUND_UP).toBigInteger().intValue();
            battleResult.setMyAddScore(addScore);
            // 扣除对面积分
            int loseScore = battleResult.getKillPatronsCount();
            if(null != goodsInfo){
                loseScore = loseScore * goodsInfo.getParamList().get(1).intValue();
            }
            //伤害增加技能加成
            BigDecimal val3 = BigDecimal.valueOf(1000 + loseScoreSkillAddition).divide(BigDecimal.valueOf(1000), CalculationManager.CALCULATION_SCALE,
                    BigDecimal.ROUND_UP);
            BigDecimal val4 = val3.multiply(BigDecimal.valueOf(loseScore));
            loseScore = val4.setScale(0, BigDecimal.ROUND_UP).toBigInteger().intValue();
            battleResult.setEnemyLoseScore(loseScore);
        }
    }

    /**
     * 增加跨服商战记录
     */
    public static void addCrossRecord(int activityId, int battleType, long myScore, int killPatronsCount, int enemyLoseScore,
             long enemyUserId, long myUserId, UserBaseInfo myBaseInfo) {
        UserTradeWarRecord record = initCrossRecord(activityId, battleType, myScore, killPatronsCount, enemyLoseScore, enemyUserId, myUserId, myBaseInfo);
        enemyAddCrossRecord(enemyUserId, record);
    }

    /**
     * 对手增加商战记录
     * @param enemyUserId
     * @param record
     */
    private static void enemyAddCrossRecord(long enemyUserId, UserTradeWarRecord record){
        GamePlayer enemyPlayer = GamePlayerMgr.getOnlinePlayer(enemyUserId);
        if (null != enemyPlayer) {
            enemyPlayer.getModule(TradeWarModule.class).addCrossRecord(record);
        } else {
            CrossTradeWarBussiness.addUserTradeWarRecord(record);
        }
    }

    /**
     * 增加跨服商战记录
     */
    public static UserTradeWarRecord initCrossRecord(int activityId, int battleType, long myScore, int killPatronsCount, int enemyLoseScore,
                                      long enemyUserId, long myUserId, UserBaseInfo myBaseInfo) {
        long nowTime = System.currentTimeMillis() / 1000;
        UserTradeWarRecord record = new UserTradeWarRecord();
        record.setActivityId(activityId);
        record.setUserId(enemyUserId);
        record.setRecordUid(UUIDHelper.randomUUID(String.valueOf(GameServer.getInstance().getServerId())));
        record.setBattleType(battleType);
        record.setEnemyUserId(myUserId);
        record.setEnemyBaseData(myBaseInfo);
        record.setEnemyScore(myScore);
        record.setKillPatronsCount(killPatronsCount);
        record.setLoseScore(enemyLoseScore);
        record.setRecordTime(nowTime);
        record.setBattle(false);
        record.setInsertOption();
        return record;
    }

    public static long getRandomServerId(ActivityInfo activityInfo,long userId){
        if(null == activityInfo){
            return 0;
        }
        //去外面拿
        int groupId = GameUnionActivityGroupMgr.getGroupId(activityInfo.getActivityId(), userId);
        if (groupId == UnionActivityGroupHelper.NO_GROUP_ID){
            return -1;
        }
        UnionActivityGroup groupData = GameUnionActivityGroupMgr.getGroupData(activityInfo.getActivityId(), groupId);

        List<UnionActivityGroupUser> userList = new ArrayList<>();
        for (UnionActivityGroupUnion union:groupData.getUnionDataMap().values()){
            ConcurrentHashMap<Long, UnionActivityGroupUser> userMap = union.getUserMap();
            //自己商会过滤
            if (userMap.containsKey(userId)){
                continue;
            }
            userList.addAll(userMap.values());
        }
        if (userList.isEmpty()){
            return 0;
        }
        int randomIndex = randomHelper.next(0, userList.size());
        UnionActivityGroupUser unionActivityGroupUser = userList.get(randomIndex);
        if (unionActivityGroupUser != null){
            return unionActivityGroupUser.getServerId();
        }
//        List<Long> serverIdList = new ArrayList<>(groupData.getServerSet());
//        if(serverIdList.size() > 0){
//            int randomIndex = randomHelper.next(0, serverIdList.size());
//            return serverIdList.get(randomIndex);
//        }
        return 0;
    }

    /**
     * 跨服商战分数变更
     * @param userId
     * @param addScore
     * @return
     */
    public static UserTradeWarInfo changeCrossTradeWarScore(long userId, int addScore) {
        UserTradeWarInfo userTradeWarInfo = TradeWarMgr.getUserTradeWarInfo(userId);
        ActivityInfo activityInfo = TradeWarActivityMgr.getInTimeActivityInfo();
        if(null == activityInfo){
            return userTradeWarInfo;
        }
        if(null != userTradeWarInfo) {
            synchronized (userTradeWarInfo) {
                userTradeWarInfo.setCrossScore(userTradeWarInfo.getCrossScore() + addScore);
                userTradeWarInfo.setModifyTime(System.currentTimeMillis() / 1000);
            }
            GamePlayer player = GamePlayerMgr.getOnlinePlayer(userId);
            if(null != player){
                //商战积分冲榜
                player.notifyListener(eGamePlayerEventType.CrossTradeWarScoreRiseRank.getValue(),
                        new UnionRiseRankArgs(UnionRiseRankArgs.NOTIFY_TYPE_NORMAL, BigInteger.valueOf(addScore), player.getUserInfo().getUnionUid()));
            }else {
                UserTradeWarBussiness.updateUserTradeWarInfo(userTradeWarInfo);
                Map<Integer, List<ActivityConditionInfo>> activityConditionInfoMap = TradeWarActivityMgr.getActivityConditionInfoMap(activityInfo.getActivityId());
                UserActivityConditionData userConditionData = null;
                UserActivityConditionData userUnionConditionData = null;
                if(null != activityConditionInfoMap && activityConditionInfoMap.size() > 0){
                    Map<Integer, List<UserActivityConditionData>> conditionDataMap = UserTradeWarActivityBussiness.getUserActivityConditionDataMap(userId, activityInfo.getActivityId());
                    //个人排行
                    int conditionType = TradeWarActivityMgr.CONDITION_TYPE_USER;
                    List<ActivityConditionInfo> activityConditionInfoList = activityConditionInfoMap.get(conditionType);
                    List<UserActivityConditionData> conditionDataList = conditionDataMap.get(conditionType);
                    if(null != conditionDataList) {
                        for (UserActivityConditionData conditionData : conditionDataList) {
                            ActivityConditionInfo conditionInfo = TradeWarActivityMgr.getActivityConditionInfo(activityInfo.getActivityId(), conditionData.getConditionId());
                            if (conditionInfo.getType() == conditionType) {
                                userConditionData = conditionData;
                                break;
                            }
                        }
                    }
                    if (null == userConditionData) {
                        userConditionData = NormalActivityMgr.initUserActivityConditionData(userId, UserMgr.getNickName(userId), BigInteger.valueOf(addScore),
                                activityInfo.getActivityId(), activityConditionInfoList.get(0).getConditionId(), activityConditionInfoList.get(0).getType());
                        UserTradeWarActivityBussiness.addUserActivityConditionData(userConditionData);
                    }else {
                        userConditionData.setValue(userConditionData.getValue().add(BigInteger.valueOf(addScore)));
                        UserTradeWarActivityBussiness.updateUserActivityConditionData(userConditionData);
                    }
                    //商会排行
                    conditionType = TradeWarActivityMgr.CONDITION_TYPE_UNION;
                    activityConditionInfoList = activityConditionInfoMap.get(conditionType);
                    conditionDataList = conditionDataMap.get(conditionType);
                    if(null != conditionDataList) {
                        for (UserActivityConditionData conditionData : conditionDataList) {
                            ActivityConditionInfo conditionInfo = TradeWarActivityMgr.getActivityConditionInfo(activityInfo.getActivityId(), conditionData.getConditionId());
                            if (conditionInfo.getType() == conditionType) {
                                userUnionConditionData = conditionData;
                                break;
                            }
                        }
                    }
                    if (null == userUnionConditionData) {
                        userUnionConditionData = NormalActivityMgr.initUserActivityConditionData(userId, UserMgr.getNickName(userId), BigInteger.valueOf(addScore),
                                activityInfo.getActivityId(), activityConditionInfoList.get(0).getConditionId(), activityConditionInfoList.get(0).getType());
                        UserTradeWarActivityBussiness.addUserActivityConditionData(userUnionConditionData);
                    }else {
                        userUnionConditionData.setValue(userUnionConditionData.getValue().add(BigInteger.valueOf(addScore)));
                        UserTradeWarActivityBussiness.updateUserActivityConditionData(userUnionConditionData);
                    }
                }
                if(null != userConditionData) {

                    int groupId = GameUnionActivityGroupMgr.getGroupId(activityInfo.getActivityId(), userId);
                    if (groupId == UnionActivityGroupHelper.NO_GROUP_ID) {
                        return userTradeWarInfo;
                    }
                    UserBaseInfo baseInfo= UserMgr.getUserBaseInfo(userId,GameServer.getInstance().getServerId());

                    UserYRank userYRank = new UserYRank();
                    userYRank.setActivityId(activityInfo.getActivityId());
                    userYRank.setGroupId(groupId);
                    userYRank.setIdKey(String.valueOf(eGamePlayerEventType.CrossTradeWarScoreRiseRank.getValue()));
                    userYRank.setUserId(userId);
                    userYRank.setUserBaseInfo(baseInfo);
                    userYRank.setValue(userConditionData.getValue());
                    userYRank.setParam(userConditionData.getParam());
                    userYRank.setUpdateTime(System.currentTimeMillis());
                    YRankMgr.addUserYRankCache(userYRank);

                    TradeWarActivityRankMgr.changeRank(activityInfo.getActivityId(), UserMgr.getUserInfo(userId), userConditionData.getValue());
                }
                if(null != userUnionConditionData){
                    String unionUid = "";
                    UnionActivityGroupUnion unionData = GameUnionActivityGroupMgr.getUnionData(activityInfo.getActivityId(), userId);
                    if (unionData != null){
                        unionUid = unionData.getUnionUid();
                    }
                    YRankMgr.uploadUnionYRank(userUnionConditionData,unionUid,UnionRiseRankArgs.NOTIFY_TYPE_NORMAL);
                }
            }
        }
        return userTradeWarInfo;
    }



    /**
     * 启动时候首次获取公告
     */
    public static void firstGetCrossNotice(){
        if(!isFirstGetCrossNotice){
            ActivityInfo activityInfo = getOpenActivityInfo();
            if(null != activityInfo) {
                CrossTradeWarProto.CrossTradeWarFirstGetNoticeReqMsg.Builder reqMsg = CrossTradeWarProto.CrossTradeWarFirstGetNoticeReqMsg.newBuilder();
                reqMsg.setActivityId(activityInfo.getActivityId());
                Map<Integer, UnionActivityGroup> map = GameUnionActivityGroupMgr.getGroupMap(activityInfo.getActivityId());
                if (map == null || map.isEmpty()){
                    return;
                }
                Map<Integer, UnionActivityGroup> groupMap = new ConcurrentHashMap<>(map);
                for (UnionActivityGroup group: groupMap.values()){
                    GamePlayerMgr.sendUnionActivityGroupPacket(CrossProtocol.C_CROSS_TRADE_WAR_FIRST_GET_NOTICE, reqMsg, 0, activityInfo.getActivityId(), group.getGroupId());
                }
            }
        }
    }

    public static boolean isIsFirstGetCrossNotice() {
        return isFirstGetCrossNotice;
    }

    public static void setIsFirstGetCrossNotice(boolean isFirst) {
        isFirstGetCrossNotice = isFirst;
    }

    /**
     * 查询玩家是否能够通缉
     * @param wantedUserId
     * @return
     */
    public static int queryUserCanWanted(int activityId,long userId, long wantedUserId){
        ActivityInfo activityInfo = TradeWarActivityMgr.getOpenActivityInfo(activityId);
        if(null == activityInfo){
            return GameErrorCode.E_ACTIVITY_NO_FOUND;
        }
        if(!ActivityMgr.activityInTime(activityInfo)){
            return GameErrorCode.E_ACTIVITY_OVER_TIME;
        }
        UserInfo wantedUserInfo = UserMgr.getUserInfo(wantedUserId);
        if(null == wantedUserInfo){
            return GameErrorCode.E_USER_NO_FOUND;
        }
        UserTradeWarInfo wantedTradeWarInfo = TradeWarMgr.getUserTradeWarInfo(wantedUserId);
        if(null == wantedTradeWarInfo){
            return GameErrorCode.E_USER_NO_FOUND;
        }
        if(!TradeWarActivityMgr.canCrossTradeWar(activityId, wantedUserId)){
            return GameErrorCode.E_CROSS_TRADE_WAR_ACTIVITY_ENEMY_NO_QUALIFIED;
        }
        if (GameUnionActivityGroupMgr.getGroupId(activityId,userId)!=GameUnionActivityGroupMgr.getGroupId(activityId,wantedUserId)){
            return GameErrorCode.E_UNION_ACTIVITY_NO_SAME_GROUP;
        }
        return 0;
    }

    /**
     * 通知通缉
     * @param tradeWarWanted
     */
    public static void worldNotifyCrossWanted(TradeWarWanted tradeWarWanted){
        TradeWarProto.TradeWarWantedNotifyMsg.Builder wantedMsg = TradeWarPb.parseTradeWarWantedNotifyMsg(false, tradeWarWanted);
        if(null != wantedMsg) {
            for (GamePlayer player : GamePlayerMgr.getCopyPlayerMap().values()) {
                if(canCrossTradeWar(tradeWarWanted.getActivityId(), player.getUserId())){
                    if (GameUnionActivityGroupMgr.getGroupId(tradeWarWanted.getActivityId(),tradeWarWanted.getUserId())==GameUnionActivityGroupMgr.getGroupId(tradeWarWanted.getActivityId(),player.getUserId())){  //同组提醒
                        if(player.getUserId() != tradeWarWanted.getWantedUserId() ||
                                tradeWarWanted.getUserBaseInfo().getServerId() != GameServer.getInstance().getServerId()) {
                            player.sendPacket(Protocol.U_CROSS_TRADE_WAR_BE_WANTED_NOTICE, wantedMsg);
                        }
                    }
                }
            }
        }
    }

    /**
     * 检测是否两人是同一个分组
     */
    public static boolean checkSameGroup(int activityId,long userId1,long userId2){
        int group1 = GameUnionActivityGroupMgr.getGroupId(activityId,userId1);
        int group2 = GameUnionActivityGroupMgr.getGroupId(activityId,userId2);
        return group1 == group2;
    }


    /**
     * 被跨服通缉处理
     * @param tradeWarWanted
     */
    public static void dealBeCrossWanted(TradeWarWanted tradeWarWanted){
        if(tradeWarWanted.getWantedBaseInfo().getServerId() == GameServer.getInstance().getServerId()){
            UserTradeWarInfo wantedTradeWarInfo = TradeWarMgr.getUserTradeWarInfo(tradeWarWanted.getWantedUserId());
            //累计被通缉次数
            wantedTradeWarInfo.setTotalBeWantedTimes(wantedTradeWarInfo.getTotalBeWantedTimes() + 1);
            GamePlayer wantedPlayer = GamePlayerMgr.getOnlinePlayer(tradeWarWanted.getWantedUserId());
            if(null != wantedPlayer){//成就、任务
                wantedPlayer.notifyListener(eGamePlayerEventType.BeWantedTotalTimes.getValue(), wantedTradeWarInfo);
                TradeWarProto.TradeWarWantedNotifyMsg.Builder beWantedMsg = TradeWarPb.parseTradeWarWantedNotifyMsg(true, tradeWarWanted);
                if(null != beWantedMsg) {
                    wantedPlayer.sendPacket(Protocol.U_CROSS_TRADE_WAR_BE_WANTED_NOTICE, beWantedMsg);
                }
            }
            String serverName = "";
            ServerInfo serverInfo = ServerListMgr.getServerInfo(tradeWarWanted.getUserBaseInfo().getServerId());
            if(null != serverInfo){
                serverName = serverInfo.getServerName();
            }
            String mailTitle = MultipleLanguageMgr.getContent(MailManager.CROSS_TRADE_WAR_BE_WANTED_TITLE, UserMgr.getLanguage(tradeWarWanted.getWantedUserId()));
            String mailContent = StringUtils.format(MultipleLanguageMgr.getContent(MailManager.CROSS_TRADE_WAR_BE_WANTED_CONTENT,
                    UserMgr.getLanguage(tradeWarWanted.getWantedUserId())), DateHelper.getCurrentDateTimeString(tradeWarWanted.getWantedTime() * 1000),
                    tradeWarWanted.getUserBaseInfo().getNickName(), serverName);
            MailManager.sendMail(tradeWarWanted.getWantedUserId(), eMailType.DAILY.getValue(), "", mailContent, mailTitle);
        }
    }

    private static Property getCrossTradeWarReward(int battleType, int killPatronsCount, int useItemId, int skillAddition, int wantedItemId){
        Property reward = new Property();
        //添加钱庄经验
        int bankExp;
        //荣誉币奖励
        long tradeWarScore;
        bankExp = TradeWarConfigMgr.getCrossBankExpReward(killPatronsCount, useItemId);
        tradeWarScore = TradeWarConfigMgr.getCrossTradeWarScoreReward(skillAddition, killPatronsCount, useItemId);
        if (battleType == eTradeWarBattleType.Track.getValue()) {
            GoodsInfo wantedGoods = GoodsMgr.getGoodsById(wantedItemId);
            if(null != wantedGoods){
                int param2 = wantedGoods.getParamList().get(1).intValue();
                tradeWarScore = param2 * tradeWarScore;   //荣誉币翻倍
            }
        }
        reward.addProperty(GameConfig.GAME_ITEM_TRADE_WAR_TAX_OFFICE, BigInteger.valueOf(bankExp));
        //加名誉币
        reward.addProperty(GameConfig.GAME_MONEY_CROSS_TRADE_WAR_SCORE, BigInteger.valueOf(tradeWarScore));

        return reward;
    }
}
